<template>
  <div class="all">
    <div class="class">
      <div class="class-header">
        <div class="header-left">
          <div class="line"></div>
          <div class="title">出差记录</div>
           <el-input
            v-model="classSearchInput"
            placeholder="请输入姓名"
            style="width: 150px"
            class="className"
           v-if="role != '3' && role != '5'"
          ></el-input>
           <el-date-picker
            v-model="currentYearMonth"
            type="month"
            placeholder="选择查询时间"
            style="width: 150px"
            value-format="YYYY-MM"
              class="className"
          ></el-date-picker>
          <div style="position: relative">
            <el-button @click="handleSearch" class="search">搜索</el-button>
            <img src="../../assets/images/搜索.png" class="searchImg" alt="" />
          </div>
        </div>
        <div class="header-right">
          <!-- <span class="currentTime">{{ currentYearMonth }}</span> -->
          <!-- 日历图标 -->
          <!-- <span class="calendar-icon" @click="handleIconClick">
            <el-icon class="custom-calendar-icon "><Calendar /></el-icon>
          </span>
          
          <el-date-picker
            v-model="currentYearMonth"
            type="month"
            format="YYYY年MM月"
            value-format="YYYY-MM"
            ref="datePickerRef"
            
            @change="handleYearMonthChange"
            style="opacity: 0; width: 0; height: 0"
          /> -->
          <el-button link type="primary" class="addRiBao" @click="handleAddBusiness" v-if=" role=='3' || role == '5' ">申请</el-button>
        </div>
      </div>
    </div>

    <div class="class-content">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="teacherName" label="姓名" align="center" />
        <el-table-column prop="city" label="出差地点" align="center" />
        <el-table-column prop="beginTime" label="出发时间" align="center" />
        <el-table-column prop="returnTime" label="返回时间" align="center" />
        <el-table-column prop="totalTime" label="出差总时长(天)" align="center" />
        <el-table-column prop="vehicle" label="交通工具" align="center" />
      </el-table>
       <div class="page">
        <el-pagination background layout="prev, pager, next" :total="total" :current-page="currentPage" :page-size="pageSize" @current-change="handleCurrentPageChange" />
        <div> 
            每页
            <el-input-number
              v-model="pageSize"
              :min="1"
              :max="30"
              controls-position="right"
              @change="handleChange"
            />条
      </div>

      </div>
    </div>
    <!-- 申请 -->
    <el-dialog v-model="dialogVisible" title="出差申请" width="400px" :show-close="false">
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px" hide-required-asterisk>
      <el-row>
        <el-form-item label="姓名" prop="name" >
          <el-input v-model="formData.name" disabled/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="formData.startTime" type="date" placeholder="请选择开始时间" style="width: 200px;" value-format="YYYY-MM-DD"/>
        </el-form-item>
      </el-row>
      <el-row>
          <el-form-item label="出差地点" prop="address" >
          <el-input v-model="formData.address" />
        </el-form-item>
        <el-form-item label="返回时间" prop="endTime">
          <el-date-picker v-model="formData.endTime" type="date" placeholder="请选择返回时间" style="width: 200px;" value-format="YYYY-MM-DD"/>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="交通工具" prop="vehicle">
          <el-input v-model="formData.vehicle" />
        </el-form-item>
        <el-form-item label="出差总时长" prop="num" v-if=false>
          <el-input v-model="formData.num" />
        </el-form-item>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false" class="cancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm" class="confirm">确认</el-button>
    </template>
  </el-dialog>
  </div>
</template>
  
<script setup>

import { ref, onMounted } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import {getBusiness,addBusiness,getBusinessInfo} from '../api/Business'
import dayjs from 'dayjs' // 引入 dayjs 库

//本地存储
const user = JSON.parse(localStorage.getItem('user'))

// 获取角色信息
const role = user.roleId

// 定义当前年月
const currentYearMonth = ref('')
// 定义日期选择器的引用
const datePickerRef = ref(null)
//搜搜
const classSearchInput = ref('')
// 表格数据
const tableData = ref([])
// 分页相关
const currentPage = ref(1) // 当前页码
const pageSize = ref(7) // 每页显示的数量
const total = ref(0) // 总记录数

// 获取表格数据
function fetchData(){
  let data = {
    pageIndex: currentPage.value, // 当前页码
    pageSize: pageSize.value, // 每页显示的数量
  }
  if(classSearchInput.value){
    data.search = classSearchInput.value
  }
  if(currentYearMonth.value){
    data.thisMonth = currentYearMonth.value 
  }
  getBusiness("outsList",data).then(res => {
    if(res.code === 200){
      tableData.value = res.dataset.outList
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}

// 个人出差信息
function fetchDataInfo(){
  let data = {
      pageIndex: currentPage.value,
        pageSize: pageSize.value,
        teacherId: user.userId,
  }  
  if(currentYearMonth.value){
    data.thisMonth = currentYearMonth.value 
  }
  getBusinessInfo("outsList2",data).then(res => {
    if(res.code === 200){
      tableData.value = res.dataset.outList2
      total.value = res.dataset.pageCount * pageSize.value 
    }
  })
}


// 页面加载时获取数据
onMounted(() => {
  if(role == 3 || role == 5){
    fetchDataInfo() 
  }else{
    fetchData()
  }
})
// 处理页码变化
const handleCurrentPageChange = (page) => {
  currentPage.value = page // 更新当前页码
  if(role == 3 || role == 5){
    fetchDataInfo() 
  }else{
    fetchData()
   }
}


// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 切换年月时重置当前页码
  if(role == 3 || role == 5){
    fetchDataInfo() 
  }else{
    fetchData()
    }
}


// 定义表单数据
const formData = ref({
  name: '',
  address: '',
  startTime: '',
  endTime: '',
  vehicle: '',
  num: '',
})
const formRef = ref(null)


// 开始时间必须在结束时间之前
const validateStartTime = (rule, value, callback) => {
  if (formData.value.endTime && value) {
    const endTime = dayjs(formData.value.endTime)
    const startTime = dayjs(value)
    if (endTime.isBefore(startTime)) {
      callback(new Error('开始时间必须在结束时间之前'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

// 结束时间必须在开始时间之后
const validateEndTime = (rule, value, callback) => {
  if (formData.value.startTime && value) {
    const startTime = dayjs(formData.value.startTime)
    const endTime = dayjs(value)
    if (endTime.isBefore(startTime)) {
      callback(new Error('结束时间必须在开始时间之后'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

// 计算出差总时长
const calculateNum = () => {
  if (formData.value.startTime && formData.value.endTime) {
    const startTime = dayjs(formData.value.startTime)
    const endTime = dayjs(formData.value.endTime)
    const days = endTime.diff(startTime, 'day')
    formData.value.num = days.toString()
  }
}

// 计算结束时间
const calculateEndTime = () => {
  if (formData.value.startTime && formData.value.num) {
    const startTime = dayjs(formData.value.startTime)
    const endTime = startTime.add(parseInt(formData.value.num), 'day')
    formData.value.endTime = endTime.format('YYYY-MM-DD')
  }
}

// 计算开始时间
const calculateStartTime = () => {
  if (formData.value.endTime && formData.value.num) {
    const endTime = dayjs(formData.value.endTime)
    const startTime = endTime.subtract(parseInt(formData.value.num), 'day')
    formData.value.startTime = startTime.format('YYYY-MM-DD')
  }
}

// 定义表单验证规则
const rules = ref({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  address: [{ required: true, message: '请输入出差地点', trigger: 'blur' }],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
    { validator: validateStartTime, trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.value.endTime) {
          calculateNum()
        } else if (value && formData.value.num) {
          calculateEndTime()
        }
        callback()
      },
      trigger: 'change',
    },
  ],
  endTime: [
    { required: true, message: '请选择返回时间', trigger: 'change' },
    { validator: validateEndTime, trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.value.startTime) {
          calculateNum()
        } else if (value && formData.value.num) {
          calculateStartTime()
        }
        callback()
      },
      trigger: 'change',
    },
  ],
  vehicle: [{ required: true, message: '请输入交通工具', trigger: 'blur' }],
  num: [
    { required: true, message: '请输入出差总时长', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (formData.value.startTime && value) {
          calculateEndTime()
        } else if (formData.value.endTime && value) {
          calculateStartTime()
        }
        callback()
      },
      trigger: 'blur',
    },
  ],
})
// 定义对话框的显示状态
const dialogVisible = ref(false);

// 点击添加按钮时显示对话框
const handleAddBusiness = () => {
  if(formRef.value){
    formRef.value.resetFields()
  }
  formData.value = {
    name: user.userName, // 假设你有一个名为 user 的对象，其中包含 name 属性
  }
  dialogVisible.value = true;
};

//添加申请出差
function AddBusiness(){
  let data = {
    teacherId: user.userId,
    teacherName: user.userName,
    city: formData.value.address,
    beginTime: formData.value.startTime,
    returnTime: formData.value.endTime,
    // totalTime: formData.value.num, 
    vehicle: formData.value.vehicle,
  }
  addBusiness("addOut",data).then(res => {
    if(res.code === 200){
      ElMessage.success('提交成功')
      if(role == 3 || role == 5){
        fetchDataInfo()
      }else{
        fetchData()
      }
      dialogVisible.value = false; 
    } 
  })
}

// 点击确认按钮时提交表单
const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
        ElMessageBox.confirm('是否提交？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning' 
        }).then(() => {
          AddBusiness() 
        }).catch(() => {
          ElMessage.info('已取消')
        })
      }
  })  
}

function handleChange() {
  currentPage.value = 1; // 切换每页显示的数量时重置当前页码
  if(role == 3 || role == 5){
    fetchDataInfo()
  }else{
    fetchData()
  }
}
</script>
  
<style scoped>
.class {
  width: 90%;
  height: 10%;
  margin-bottom: 20px;
  margin-top: 20px;
}
/* 头部左侧 */
.header-left {
  display: flex;
  align-items: center;
  margin-left: 40px;
}
.line {
  width: 2px;
  height: 20px;
  background-color: #007bff;
}
.title {
  padding-left: 10px;
  font-size: 20px;
  margin-right: 20px;
}
.className {
  margin-right: 10px;
}
.line2 {
  width: 10px;
  height: 2px;
  margin-left: 5px;
  margin-right: 5px;
  background-color: #9b9b9b;
}
:deep(.className .el-input__wrapper){
  border-radius: 12px !important;
}
.search {
  background-color: #0f6ab1;
  color: #fff;
  border: none;
  margin-left: 10px;
  border-radius: 16px;
  padding: 0;
  padding-right: 15px;
  padding-left: 36px;
}
.searchImg {
  position: absolute;
  top: 8px;
  left: 25px;
}
/* 头部右侧 */
.header-right {
  display: flex;
  align-items: center;
  margin-right: 40px;
}
.currentTime{
  font-size: 15px;
  margin-right: 10px;
}
.calendar-icon {
  display: flex ;
  align-items: center; 
}
.custom-calendar-icon {
  font-size: 20px; /* 可以根据需要调整图标大小 */
}
.addRiBao {
margin-left: 10px;
font-size: 15px;
}


/* 表格区域 */
.class-content {
  width: 90%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 表格数据 */
:deep(.el-table thead th) {
  background-color: #fbfcff !important;
}
:deep(.el-table .cell) {
  color: black;
}
:deep(.details1) {
  margin-left: 55px;
}
/* 报告不能换行 */
:deep(.el-table__body-wrapper .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/* 分页 */
.page {
  margin-top: 50px;
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;

}
/* 分页背景色 */
:deep(.el-pager .is-active) {
  background-color: #0f6ab1 !important;
}
/* 模态框 */
:deep(.el-overlay .el-overlay-dialog) {
position: absolute;
}
:deep(.el-overlay) {
position: absolute;
}
:deep(.el-dialog__body){
  display: flex;
  justify-content: center;
}
:deep(.el-dialog) {
padding: 0px;
width: 800px;
}
:deep(.el-dialog header span) {
display: inline-block;
width: 100%;
background-color: #0f6ab1;
height: 40px;
color: white;
font-size: 15px;
text-align: center;
line-height: 40px;
}
:deep(.el-dialog__footer) {
text-align: center;
padding-bottom: 20px;
}
:deep(.confirm) {
margin-left: 50px;
background-color: #0f6ab1;
}
:deep(.cancel) {
background-color: #0f6ab1;
color: white;
}


</style>